import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Input, Drawer, Image, Popconfirm, Select } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import FormItem from 'antd/lib/form/FormItem';
import {
  queryRule,
  updateRule,
  addRule,
  removeRule,
  queryHardWarRule,
  updateModelRule,
  queryBindHardWarRule,
} from './service';
import { handleReturnArray } from '@/utils/utils';
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async (payload, actionRef) => {
  const hide = message.loading('正在修改');

  try {
    await updateRule(payload);
    hide();
    message.success('修改成功');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

const handleModelUpdate = async (payload, actionRef) => {
  const hide = message.loading('正在绑定');

  try {
    await updateModelRule(payload);
    hide();
    message.success('绑定成功');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('绑定失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (payload, actionRef) => {
  const hide = message.loading('正在删除');

  try {
    await removeRule(payload);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createEditModalVisible, handleEditModalVisible] = useState(false);
  const [createHardWareModalVisible, handleHardWareModalVisible] = useState(false);
  const [count, setCount] = useState({});
  const [hardWareCount, setHardWareCount] = useState(null);
  const [row, setRow] = useState(null);
  const [formValue, setFormValue] = useState(null);
  const [selectedRowsState, setSelectedRows] = useState([]);
  const actionRef = useRef();
  const handleQueryHardWare = async (payload) => {
    try {
      const response = await queryBindHardWarRule({ modelId: payload });
      const { data } = response;
      const hardWareArray = [];
      data.map((item) => {
        hardWareArray.push(item.id);
      });
      setSelectedRows(hardWareArray);
      return true;
    } catch (error) {
      return false;
    }
  };
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '机型名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '机型库存',
      dataIndex: 'stock',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '机型型号',
      dataIndex: 'model',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '机型售价',
      dataIndex: 'price',
      valueType: 'text',
      hideInSearch: true,
    },
    // {
    //   title: '机型类型',
    //   dataIndex: 'type',
    //   valueEnum: {
    //     0: {
    //       text: '基础版',
    //       status: 'Default',
    //       value: '基础版',
    //     },
    //     1: {
    //       text: '升级版',
    //       status: 'Success',
    //       value: '升级版',
    //     },
    //     2: {
    //       text: '完整版',
    //       status: 'Success',
    //       value: '完整版',
    //     },
    //   },
    //   renderFormItem: (item, { defaultRender, ...rest }, form) => {
    //     return (
    //       <FormItem name="type" label={false}>
    //         <Select placeholder="请选择">
    //           {handleReturnArray(item.valueEnum, 3).map((item_in, index) => {
    //             if (item_in) {
    //               return (
    //                 <Option key={index} value={item_in.value}>
    //                   {item_in.text}
    //                 </Option>
    //               );
    //             }
    //           })}
    //         </Select>
    //       </FormItem>
    //     );
    //   },
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleEditModalVisible(true);
              setFormValue(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleHardWareModalVisible(true);
              handleQueryHardWare(record.id);
              setRow(record);
            }}
          >
            硬件管理
          </a>
          <Divider type="vertical" />
          <Popconfirm
            placement="top"
            title="确定要删除吗?"
            onConfirm={() => {
              handleRemove(record.id, actionRef);
            }}
            okText="Yes"
            cancelText="No"
          >
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  const hardWareColumns = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '硬件名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '硬件数量',
      dataIndex: 'count',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '硬件型号',
      dataIndex: 'sn',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '硬件规格',
      dataIndex: 'spec',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '硬件单价',
      dataIndex: 'unitPrice',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '硬件照片',
      dataIndex: 'url',
      valueType: 'text',
      width: 200,
      hideInSearch: true,
      render: (_, payload) => {
        return (
          <>
            {' '}
            <Image style={{ maxHeight: '50px' }} src={_} />{' '}
          </>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            {formValue ? (
              <FormItem name="facePicture">
                <UploadImg imgUrl={facePicture} handleSetFacePicture={handleSetFacePicture} />
              </FormItem>
            ) : (
              <FormItem name="facePicture">
                <UploadImg handleSetFacePicture={handleSetFacePicture} />
              </FormItem>
            )}
          </>
        );
      },
    },
    {
      title: '是否中间件支撑',
      dataIndex: 'support',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '否',
          status: 'Error',
          value: 0,
        },
        1: {
          text: '是',
          status: 'Success',
          value: 1,
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem name="support" label={false}>
            <Select placeholder="请选择">
              {handleReturnArray(item.valueEnum, 2).map((item_in, index) => {
                if (item_in) {
                  return (
                    <Select.Option key={index} value={item_in.value}>
                      {item_in.text}
                    </Select.Option>
                  );
                }
              })}
            </Select>
          </FormItem>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="机型列表"
        actionRef={actionRef}
        bordered
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 添加机型
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        postData={(params) => {
          const { list, total } = params;
          setCount(total);
          return list;
        }}
        columns={columns}
        rowSelection={false}
      />
      <CreateForm
        title="添加机型"
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        width={null}
      >
        <ProTable
          onSubmit={async (value) => {
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        title="修改机型"
        onCancel={() => handleEditModalVisible(false)}
        modalVisible={createEditModalVisible}
        width={null}
      >
        <ProTable
          onSubmit={async (value) => {
            value.version = formValue.version + 1;
            value.id = formValue.id;
            const success = await handleUpdate(value, actionRef);

            if (success) {
              handleEditModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{ initialValues: formValue }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        title="硬件管理"
        onCancel={() => handleHardWareModalVisible(false)}
        modalVisible={createHardWareModalVisible}
        width={1200}
      >
        <ProTable
          headerTitle="硬件列表"
          // actionRef={actionRef}
          bordered
          rowKey="id"
          search={{
            labelWidth: 80,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              onClick={() => {
                // handleModalVisible(true);
                const hardwareList = [];
                selectedRowsState.map((item) => {
                  hardwareList.push({ hardwareId: item, modelId: row.id });
                });
                handleModelUpdate(hardwareList, actionRef);
                handleHardWareModalVisible(false);
              }}
            >
              <PlusOutlined /> 确定
            </Button>,
          ]}
          options={false}
          request={(params, sorter, filter) => queryHardWarRule({ ...params, sorter, filter })}
          pagination={{
            defaultPageSize: 30,
            showSizeChanger: false,
            showTitle: false,
            total: hardWareCount,
            showTotal: (total) => `共${total}条`,
          }}
          postData={(params) => {
            const { list, total } = params;
            setHardWareCount(total);
            return list;
          }}
          columns={hardWareColumns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              const selectArray = [];
              selectedRows.map((item) => {
                selectArray.push(item.id);
              });
              setSelectedRows(selectArray);
            },
            selectedRowKeys: selectedRowsState,
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
